package com.limeng.servlets;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.limeng.domain.DAOAddress;
import com.limeng.domain.DAOContact;
import com.limeng.exceptions.DAOException;
import com.limeng.model.Address;
import com.limeng.model.Contact;

/**
 * Servlet implementation class NewContact
 */
public class NewContact extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public NewContact() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
      
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType( "text/html" );
		PrintWriter out = response.getWriter();
		out.println( "<html><body>" );
		
		String firstName=request.getParameter("firstname");
		String lastName=request.getParameter("lastname");
		String email=request.getParameter("email");
		String addressId=request.getParameter("address");
		
		
		out.println( "First Name="+firstName+"</br>");
		out.println( "Last Name="+lastName+"</br>");
		out.println( "Email="+email+"</br>");
		
		Contact contact=new Contact();
		contact.setFirstName(firstName);
		contact.setLastName(lastName);
		contact.setEmail(email);
		
		//For test case, need to improve
		
		Address address=null;
		try {
			address = DAOAddress.getInstance().loadAddress(1L);
		} catch (DAOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		contact.setAddress(address);
		if(address==null)
		{
		out.println( "<h1> "+ "address is null"+"</h1>" );
		}
		try {
			DAOContact.getInstance().saveContact(contact);
			out.println( "<h1> "+ "new contact has been saved"+"</h1>" );
			
		} catch (DAOException e) {
			out.println( "<h1> "+ "save failed"+"</h1>" );
			e.printStackTrace();
		}
		out.println("<html><body>");		
		}

}
